<template>
  <div class="map-wrapper">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <svg t="1686036128495" viewBox="0 0 1024 1024" width="24" height="24">
        <path d="M671.968 912c-12.288 0-24.576-4.672-33.952-14.048L286.048 545.984c-18.752-18.72-18.752-49.12 0-67.872l351.968-352c18.752-18.752 49.12-18.752 67.872 0 18.752 18.72 18.752 49.12 0 67.872L387.872 512l318.016 318.016c18.752 18.752 18.752 49.12 0 67.872C696.544 907.328 684.256 912 671.968 912z" fill="#ffffff"></path>
      </svg>
      <span>返回</span>
    </div>
    
    <!-- 地图容器 -->
    <div id="container" class="container"></div>
    
    <!-- 面板控制按钮 -->
    <div class="panel-control" @click="togglePanel">
      <div class="panel-arrow" :class="{ 'is-up': isPanelVisible }">
        <svg viewBox="0 0 1024 1024" width="16" height="16">
          <path d="M512 676.096l-346.624-346.624 45.248-45.248L512 584.448l301.376-301.376 45.248 45.248z" fill="#ffffff"></path>
        </svg>
      </div>
    </div>
    
    <!-- 搜索栏和地点列表 -->
    <div class="bottom-panel" :class="{ 'is-visible': isPanelVisible }">
      <!-- 添加可点击的横杠区域 -->
      <div class="handle-area" @click="togglePanel">
        <div class="handle-bar"></div>
      </div>
      
      <div class="search-box">
        <div class="search-container">
          <div class="search-icon">
            <svg viewBox="0 0 1024 1024" width="20" height="20">
              <path d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6c3.2 3.2 8.4 3.2 11.6 0l43.6-43.5c3.2-3.2 3.2-8.4 0-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z" fill="#999"></path>
            </svg>
          </div>
          <input 
            type="text" 
            class="search-input" 
            placeholder="请输入目的地:"
            ref="inputRef"
            @focus="onSearchFocus"
            @input="onSearchInput"
            @keyup.enter="searchCurrentInput"
            v-model="searchKeyword"
          />
          <div class="search-button" @click="searchCurrentInput">搜索</div>
        </div>
      </div>
      
      <!-- 附近目的地列表 -->
      <div class="poi-list">
        <!-- 搜索提示列表 -->
        <div v-if="searchVisible && searchTips.length > 0">
          <h3 class="nearby-title">搜索结果</h3>
          <div 
            class="poi-item" 
            v-for="(tip, index) in searchTips" 
            :key="index"
            @click="selectSearchTip(tip)"
          >
            <div class="poi-info">
              <div class="poi-name">{{ tip.name }}</div>
              <div class="poi-distance" v-if="tip.district">{{ tip.district }}</div>
            </div>
            <button class="set-button" @click="selectSearchTip(tip)">选择</button>
          </div>
        </div>
        
        <!-- 默认显示附近目的地 -->
        <div v-else>
          <h3 class="nearby-title">附近目的地</h3>
          <div class="poi-item" v-for="(poi, index) in nearbyPOIs" :key="index">
            <div class="poi-info">
              <div class="poi-name">{{ poi.name }}</div>
              <div class="poi-distance">距离您 {{ poi.distance }}</div>
            </div>
            <button class="set-button" @click="setPOIAsDestination(poi)">设置</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';

// 声明高德地图全局变量
declare global {
  interface Window {
    AMap: any;
    _AMapSecurityConfig: any;
    initAMap: () => void;
  }
}

interface Position {
  lng: number;
  lat: number;
}

interface DrivingRoute {
  routes: {
    steps: {
      path: Position[];
    }[];
  }[];
}

interface POI {
  id: string;
  name: string;
  location: [number, number];
  distance: string;
}

interface SearchTip {
  id: string;
  name: string;
  district: string;
  address?: string;
  location?: {
    lng: number;
    lat: number;
  };
  adcode?: string;
}

export default defineComponent({
  name: 'MapContainer',
  setup() {
    const router = useRouter();
    const inputRef = ref<HTMLInputElement | null>(null);
    let map: any = null;
    let placeSearch: any = null;
    let auto: any = null;
    let geolocation: any = null;
    let driving: any = null;
    let currentPosition: [number, number] | null = null;
    let carMarker: any = null;
    let timer: number | null = null;
    let stepIndex = 0;
    let AMap: any = null;
    let centerMarker: any = null;
    let circleArea: any = null;
    let markers: any[] = [];
    const stepDistance = 1; // 每次移动的距离，可自定义
    const searchVisible = ref(false);
    const searchKeyword = ref('');
    const searchTips = ref<SearchTip[]>([]);
    const searchTimeout = ref<number | null>(null);
    const isMapLoaded = ref(false);
    const isAutoCompleteLoaded = ref(false);
    const isPanelVisible = ref(true); // 默认显示底部面板

    // 附近POI数据
    const nearbyPOIs = ref<POI[]>([
      {
        id: '1',
        name: '万象城',
        location: [116.307629, 39.984751],
        distance: '2km'
      },
      {
        id: '2',
        name: '泉城广场',
        location: [116.317629, 39.994751],
        distance: '3.5km'
      },
      {
        id: '3',
        name: '芙蓉街',
        location: [116.327629, 39.974751],
        distance: '2km'
      }
    ]);

    // 返回上一页
    const goBack = () => {
      router.back();
    };

    // 搜索框获取焦点
    const onSearchFocus = () => {
      searchVisible.value = true;
      isPanelVisible.value = true;
      if (searchKeyword.value.trim().length >= 2) {
        getSearchTips(searchKeyword.value);
      }
    };
    
    // 搜索框输入事件
    const onSearchInput = () => {
      // 清除之前的延时
      if (searchTimeout.value) {
        clearTimeout(searchTimeout.value);
      }
      
      // 确保搜索提示可见
      searchVisible.value = true;
      
      // 设置延时，避免频繁请求
      searchTimeout.value = window.setTimeout(() => {
        const keyword = searchKeyword.value.trim();
        // 只有当输入字符大于等于2个时才触发搜索
        if (keyword.length >= 2) {
          getSearchTips(keyword);
        } else {
          searchTips.value = [];
        }
      }, 300);
    };
    
    // 直接搜索当前输入内容
    const searchCurrentInput = () => {
      const keyword = searchKeyword.value.trim();
      if (keyword.length >= 2 && placeSearch) {
        // 保持searchVisible为true，确保搜索结果显示在面板内
        searchVisible.value = true;
        // 确保面板保持可见
        isPanelVisible.value = true;
        placeSearch.search(keyword);
      }
    };
    
    // 获取搜索提示
    const getSearchTips = (keyword: string) => {
      if (!isAutoCompleteLoaded.value || !auto || !keyword || keyword.length < 2) return;
      
      console.log('获取搜索提示:', keyword);
      
      try {
        auto.search(keyword, (status: string, result: any) => {
          console.log('搜索提示结果状态:', status);
          console.log('搜索提示结果:', result);
          
          if (status === 'complete' && result.tips && result.tips.length > 0) {
            // 处理搜索提示结果
            searchTips.value = result.tips.map((tip: any) => ({
              id: tip.id || String(Math.random()),
              name: tip.name,
              district: tip.district,
              address: tip.address || tip.district,
              location: tip.location,
              adcode: tip.adcode
            }));
            
            // 确保搜索提示可见
            searchVisible.value = true;
          } else {
            searchTips.value = [];
            console.log('未找到搜索提示或搜索提示为空');
            
            // 如果没有提示但有关键词，尝试直接搜索
            if (keyword.length > 2 && placeSearch) {
              placeSearch.search(keyword);
            }
          }
        });
      } catch (error) {
        console.error('获取搜索提示出错:', error);
        searchTips.value = [];
      }
    };
    
    // 选择搜索提示
    const selectSearchTip = (tip: SearchTip) => {
      searchKeyword.value = tip.name;
      searchTips.value = [];
      // 保持搜索提示可见，确保结果在面板中显示
      searchVisible.value = true;
      // 确保底部面板保持可见
      isPanelVisible.value = true;
      
      // 如果提示有位置信息，直接使用
      if (tip.location) {
        planRoute(tip.name, [tip.location.lng, tip.location.lat]);
      } else {
        // 如果提示没有位置信息，使用搜索服务查询
        if (placeSearch) {
          if (tip.adcode) {
            placeSearch.setCity(tip.adcode);
          }
          placeSearch.search(tip.name);
        }
      }
    };

    // 设置POI为目的地
    const setPOIAsDestination = (poi: POI) => {
      if (!map) return;
      
      planRoute(poi.name, poi.location);
    };

    // 规划路线的通用函数
    const planRoute = (destName: string, destLocation: [number, number]) => {
      if (!map || !AMap || !currentPosition) {
        console.error("无法规划路线：地图、AMap或当前位置未初始化");
        return;
      }
      
      try {
        console.log("开始规划路线:", currentPosition, "到", destLocation);
        
        // 清除之前的路线和标记，但保留当前位置标记和圆圈
        const overlays = map.getAllOverlays();
        overlays.forEach((overlay: any) => {
          if (overlay !== centerMarker && overlay !== circleArea) {
            map.remove(overlay);
          }
        });
        
        // 保持起点标记为蓝色圆圈
        // 不需要更改样式，保持蓝色圆圈标记
        if (centerMarker) {
          centerMarker.setTitle("起点");
        }
        
        // 添加终点标记
        const endMarker = new AMap.Marker({
          position: destLocation,
          map: map,
          title: destName,
          icon: new AMap.Icon({
            size: new AMap.Size(25, 34),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-end.png',
            imageSize: new AMap.Size(25, 34)
          })
        });
        
        // 确保初始化驾车路线规划实例
        if (!driving) {
          driving = new AMap.Driving({
            map: map,
            panel: false,
            policy: AMap.DrivingPolicy.LEAST_TIME, // 最快捷模式
            autoFitView: true
          });
        }
        
        // 规划驾车路线
        console.log(`规划路线：从当前位置 ${currentPosition} 到 ${destName} ${destLocation}`);
        
        driving.search(
          currentPosition, 
          destLocation, 
          { waypoints: [] }, 
          function(status: string, result: any) {
            console.log("路线规划返回状态:", status);
            console.log("路线规划返回结果:", result);
            
            if (status === 'complete') {
              console.log('驾车路线规划成功');
              
              // 显示路线轨迹
              if (result.routes && result.routes.length > 0) {
                const routeInfo = result.routes[0];
                const distance = routeInfo.distance;
                const time = routeInfo.time;
                
                // 计算驾车时间
                const hours = Math.floor(time / 3600);
                const minutes = Math.floor((time % 3600) / 60);
                let timeStr = '';
                if (hours > 0) {
                  timeStr += `${hours}小时`;
                }
                if (minutes > 0) {
                  timeStr += `${minutes}分钟`;
                }
                
                // 计算驾车距离
                let distanceStr = '';
                if (distance >= 1000) {
                  distanceStr = `${(distance / 1000).toFixed(1)}公里`;
                } else {
                  distanceStr = `${distance}米`;
                }
                
                // 显示路线信息
                const routeInfoDiv = document.createElement('div');
                routeInfoDiv.className = 'route-info';
                routeInfoDiv.innerHTML = `
                  <div class="route-info-panel">
                    <div class="route-title">路线详情</div>
                    <div class="route-detail">
                      <div class="route-destination">目的地: ${destName}</div>
                      <div class="route-distance">距离: ${distanceStr}</div>
                      <div class="route-time">预计用时: ${timeStr}</div>
                    </div>
                  </div>
                `;
                
                // 先移除已有的路线信息面板(如果存在)
                const existingPanel = document.querySelector('.route-info');
                if (existingPanel) {
                  existingPanel.remove();
                }
                
                document.querySelector('.map-wrapper')?.appendChild(routeInfoDiv);
                
                // 10秒后自动移除路线信息面板
                setTimeout(() => {
                  document.querySelector('.route-info')?.remove();
                }, 10000);
                
                // 确保路线显示在地图上
                map.setFitView([centerMarker, endMarker]);
              }
            } else {
              console.error('驾车路线规划失败', result);
              // 显示错误提示
              const errorMsg = document.createElement('div');
              errorMsg.className = 'route-info';
              errorMsg.innerHTML = `
                <div class="route-info-panel route-error">
                  <div class="route-title">路线规划失败</div>
                  <div class="route-detail">
                    <div>无法找到从当前位置到${destName}的路线</div>
                  </div>
                </div>
              `;
              
              // 先移除已有的路线信息面板(如果存在)
              const existingPanel = document.querySelector('.route-info');
              if (existingPanel) {
                existingPanel.remove();
              }
              
              document.querySelector('.map-wrapper')?.appendChild(errorMsg);
              
              // 5秒后自动移除错误提示
              setTimeout(() => {
                document.querySelector('.route-info')?.remove();
              }, 5000);
            }
          }
        );
      } catch (error) {
        console.error("规划路线时出错:", error);
      }
    };

    // 初始化地图
    const initMap = () => {
      // @ts-ignore: AMap安全配置属性
      window._AMapSecurityConfig = {
        securityJsCode: "bc85185b03fc9a32c0a1f023a1addd87",
      };

      // 使用脚本标签直接加载高德地图API
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.async = true;
      script.src = 'https://webapi.amap.com/maps?v=2.0&key=0710f43e6881294242c7d4d1eb47d192&plugin=AMap.Geolocation,AMap.PlaceSearch,AMap.Autocomplete,AMap.Driving&callback=initAMap';
      
      // 定义全局回调函数
      window.initAMap = () => {
        console.log("地图API加载成功");
        AMap = window.AMap;
        initMapInstance();
      };
      
      script.onerror = (e) => {
        console.error("地图API加载失败:", e);
      };
      document.head.appendChild(script);
    };
    
    // 初始化地图实例
    const initMapInstance = () => {
      if (!AMap) {
        console.error("AMap未加载");
        return;
      }
      
      try {
        // 创建地图实例
        map = new AMap.Map("container", {
          pitch: 50,
          viewMode: "3D",
          rotateEnable: true,
          pitchEnable: true,
          zoom: 17,
          rotation: -15,
          zooms: [2, 20],
          center: [116.397428, 39.90923],
          resizeEnable: true,
          mapStyle: 'amap://styles/normal',
          features: ['bg', 'road', 'building', 'point'],
          showBuildingBlock: true, // 显示建筑物块
          showIndoorMap: true // 显示室内图
        });

        map.on("complete", function () {
          console.log("地图加载完成");
          isMapLoaded.value = true;
          
          // 使用AMap.plugin确保插件加载完成后再使用
          AMap.plugin([
            'AMap.Geolocation',
            'AMap.PlaceSearch',
            'AMap.AutoComplete',
            'AMap.Driving',
            'AMap.ControlBar',
            'AMap.ToolBar',
            'AMap.Scale',
            'AMap.MapType'
          ], function(){
            console.log('所有插件加载完成');
            
            // 添加3D控制器，放置在右上角
            const controlBar = new AMap.ControlBar({
              position: {
                right: '10px',
                top: '10px'
              },
              showZoomBar: true,
              showControlButton: true
            });
            map.addControl(controlBar);
            
            // 添加工具条，放置在右下角
            const toolBar = new AMap.ToolBar({
              position: {
                right: '10px',
                bottom: '80px'
              }
            });
            map.addControl(toolBar);
            
            // 添加比例尺，放置在左下角
            const scale = new AMap.Scale({
              position: {
                left: '10px',
                bottom: '10px'
              }
            });
            map.addControl(scale);
            
            // 添加地图类型切换控件，放在右上角罗盘控件下方
            const mapType = new AMap.MapType({
              position: {
                right: '10px',
                top: '120px'
              },
              defaultType: 0, // 默认显示标准地图
              showRoad: true, // 显示路网
              showLabel: true // 显示标签
            });
            map.addControl(mapType);
            
            // 确保所有地图类型都支持3D视图
            // 设置卫星图层为3D
            const satelliteLayer = new AMap.TileLayer.Satellite({
              zIndex: 10,
              zooms: [2, 20],
              visible: false
            });
            map.add(satelliteLayer);
            
            // 添加路网图层
            const roadNetLayer = new AMap.TileLayer.RoadNet({
              zIndex: 11,
              zooms: [2, 20],
              visible: false
            });
            map.add(roadNetLayer);
            
            // 添加建筑物图层
            const buildingLayer = new AMap.Buildings({
              zIndex: 12,
              zooms: [16, 20],
              heightFactor: 2 // 高度系数
            });
            map.add(buildingLayer);
            
            // 监听地图类型切换事件，确保所有地图类型都使用3D视图
            map.on('maptypechange', function(e: any) {
              console.log('地图类型切换:', e, '当前视图模式:', map.getViewMode());
              
              // 强制设置为3D视图，无论当前是什么模式
              setTimeout(() => {
                // 使用延时确保在地图类型切换完成后再设置3D视图
                map.setViewMode('3D');
                map.setPitch(50);
                map.setRotation(-15);
                
                // 根据地图类型调整图层显示
                const mapType = e.target.getMapType();
                
                // 如果是卫星图，确保建筑物和路网可见
                if (mapType === 'satellite') {
                  // 确保卫星图层可见
                  satelliteLayer.setVisible(true);
                  // 显示路网
                  roadNetLayer.setVisible(true);
                  // 显示建筑物
                  buildingLayer.setVisible(true);
                } else {
                  // 标准地图模式
                  satelliteLayer.setVisible(false);
                  roadNetLayer.setVisible(false);
                  // 保持建筑物可见
                  buildingLayer.setVisible(true);
                }
                
                console.log('已设置为3D视图，当前视图模式:', map.getViewMode(), '地图类型:', mapType);
              }, 200);
            });
            
            // 初始化自动完成
            initAutoComplete();
            
            // 初始化驾车路线规划
            driving = new AMap.Driving({
              map: map,
              panel: false,
              policy: AMap.DrivingPolicy.LEAST_TIME, // 最快捷模式
              autoFitView: true
            });
            
            // 初始化定位
            initGeolocation();
          });
        });
      } catch (error) {
        console.error("初始化地图实例失败:", error);
      }
    };
    
    // 初始化自动完成
    const initAutoComplete = () => {
      try {
        console.log("初始化自动完成组件");
        
        // 初始化自动完成 - 修正构造函数名称为 AutoComplete (首字母C大写)
        // 不再直接绑定到输入框，而是由我们自己控制
        auto = new AMap.AutoComplete({
          city: '全国',
          citylimit: false,
          datatype: 'all', // 返回所有数据类型
          // 移除对input元素的直接绑定，避免显示默认的下拉框
          input: null
        });
        
        // 初始化地点搜索
        placeSearch = new AMap.PlaceSearch({
          map: map,
          pageSize: 10,
          pageIndex: 1,
          extensions: 'all'
        });

        placeSearch.on("complete", function (data: any) {
          console.log("搜索结果:", data);
          
          if (data.poiList && data.poiList.pois.length > 0) {
            const firstPoi = data.poiList.pois[0];
            const destPos: [number, number] = [firstPoi.location.lng, firstPoi.location.lat];
            
            // 使用规划路线函数
            planRoute(firstPoi.name, destPos);
          } else {
            console.log("未找到相关结果");
          }
        });
        
        isAutoCompleteLoaded.value = true;
        console.log("自动完成组件加载成功");
      } catch (error) {
        console.error("初始化自动完成组件失败:", error);
      }
    };
    
    // 初始化定位
    const initGeolocation = () => {
      try {
        if (AMap && AMap.Geolocation) {
          geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            buttonPosition: 'RB',  // 右下角
            buttonOffset: new AMap.Pixel(10, 20),
            zoomToAccuracy: true,
            showMarker: false, // 不显示默认标记，我们将自定义标记
            showCircle: false  // 不显示默认精度圆圈，我们将自定义圆圈
          });

          map.addControl(geolocation);
  
          // 获取当前位置
          geolocation.getCurrentPosition(function (status: string, result: any) {
            if (status === 'complete') {
              console.log("定位成功", result.position);
              currentPosition = [result.position.lng, result.position.lat];
              map.setCenter(result.position);
              
              // 移除地图上已有的定位标记和圆圈
              if (map.getAllOverlays('marker').length > 0) {
                const existingMarkers = map.getAllOverlays('marker');
                existingMarkers.forEach((marker: any) => {
                  if (marker.getTitle() === "当前位置" || marker.getTitle() === "定位点") {
                    map.remove(marker);
                  }
                });
              }
              if (map.getAllOverlays('circle').length > 0) {
                const existingCircles = map.getAllOverlays('circle');
                map.remove(existingCircles);
              }
              
              // 创建自定义精度圆圈
              const circle = new AMap.Circle({
                center: result.position,
                radius: result.accuracy || 100, // 精度半径，如果没有则默认100米
                fillColor: '#1791fc22', // 蓝色，低透明度
                strokeColor: '#1791fc', // 蓝色边框
                strokeWeight: 1,
                zIndex: 100
              });
              map.add(circle);
              
              // 创建起点标记 - 使用蓝色圆圈标记
              const startMarker = new AMap.Marker({
                position: result.position,
                map: map,
                title: "当前位置",
                content: '<div class="location-circle"></div>',
                offset: new AMap.Pixel(-8, -8), // 圆圈直径16px，偏移量为半径
                zIndex: 200 // 确保标记在最上层
              });
              
              // 保存标记和圆圈的引用，方便后续更新
              centerMarker = startMarker;
              circleArea = circle;
              
              // 定位成功后，搜索附近POI
              searchNearbyPOIs(result.position);
            } else {
              console.error("定位失败", result.message);
            }
          });
        } else {
          console.error("AMap.Geolocation 未正确加载");
        }
      } catch (error) {
        console.error("初始化定位组件失败:", error);
      }
    };
    
    // 搜索附近POI
    const searchNearbyPOIs = (position: any) => {
      if (!AMap || !position) return;
      
      try {
        const nearbySearch = new AMap.PlaceSearch({
          type: '餐饮服务|购物服务|生活服务|体育休闲服务',
          pageSize: 10,
          pageIndex: 1,
          extensions: 'all'
        });
        
        nearbySearch.searchNearBy('', [position.lng, position.lat], 3000, (status: string, result: any) => {
          if (status === 'complete' && result.poiList && result.poiList.pois.length > 0) {
            console.log("附近POI搜索结果:", result.poiList.pois);
            
            // 更新POI列表
            updateNearbyPOIs(result.poiList.pois);
          }
        });
      } catch (error) {
        console.error("搜索附近POI失败:", error);
      }
    };
    
    // 更新附近POI列表
    const updateNearbyPOIs = (pois: any[]) => {
      const processedPOIs: POI[] = [];
      
      pois.forEach((poi: any) => {
        if (poi.location && poi.distance !== undefined) {
          // 计算距离显示
          let distance: string;
          if (poi.distance < 1000) {
            distance = `${Math.round(poi.distance)}m`;
          } else {
            distance = `${(poi.distance / 1000).toFixed(1)}km`;
          }
          
          processedPOIs.push({
            id: poi.id || String(Math.random()),
            name: poi.name,
            location: [poi.location.lng, poi.location.lat],
            distance: distance
          });
        }
      });
      
      // 更新POI列表
      if (processedPOIs.length > 0) {
        nearbyPOIs.value = processedPOIs;
      }
    };

    const calculateBearing = (from: Position, to: Position): number => {
      const fromLat = (from.lat * Math.PI) / 180;
      const fromLng = (from.lng * Math.PI) / 180;
      const toLat = (to.lat * Math.PI) / 180;
      const toLng = (to.lng * Math.PI) / 180;
      const dLng = toLng - fromLng;
      const y = Math.sin(dLng) * Math.cos(toLat);
      const x = Math.cos(fromLat) * Math.sin(toLat) - Math.sin(fromLat) * Math.cos(toLat) * Math.cos(dLng);
      const bearing = (Math.atan2(y, x) * 180) / Math.PI;
      return (bearing + 360) % 360;
    };

    // 切换面板显示/隐藏
    const togglePanel = () => {
      isPanelVisible.value = !isPanelVisible.value;
      
      // 添加动画效果和触觉反馈
      if (isPanelVisible.value) {
        // 如果是移动设备且支持振动API，添加轻微振动反馈
        if ('vibrate' in navigator) {
          try {
            navigator.vibrate(15); // 轻微振动15毫秒
          } catch (e) {
            console.log('振动API不可用');
          }
        }
      }
    };

    onMounted(() => {
      initMap();
      
      // 点击地图区域时，不会关闭面板
      document.addEventListener('click', (e: MouseEvent) => {
        const target = e.target as HTMLElement;
        // 如果点击的是地图区域，不改变面板状态
        if (!target.closest('.search-box') && !target.closest('.bottom-panel') && !target.closest('.panel-control')) {
          // 不设置isPanelVisible的值，确保点击其他区域不影响面板状态
        }
      });
      
      // 添加滑动手势支持
      setTimeout(() => {
        let touchStartY = 0;
        let touchEndY = 0;
        const bottomPanel = document.querySelector('.bottom-panel');
        const handleArea = document.querySelector('.handle-area');
        
        if (handleArea) {
          handleArea.addEventListener('touchstart', (e) => {
            // 使用类型断言避免TypeScript错误
            const touchEvent = e as unknown as TouchEvent;
            touchStartY = touchEvent.touches[0].clientY;
          }, { passive: true });
          
          handleArea.addEventListener('touchmove', (e) => {
            // 使用类型断言避免TypeScript错误
            const touchEvent = e as unknown as TouchEvent;
            touchEndY = touchEvent.touches[0].clientY;
            const deltaY = touchEndY - touchStartY;
            
            // 向上滑动展开面板
            if (deltaY < -30 && !isPanelVisible.value) {
              isPanelVisible.value = true;
              if ('vibrate' in navigator) {
                try { navigator.vibrate(15); } catch (e) {}
              }
            }
            // 向下滑动收起面板
            else if (deltaY > 30 && isPanelVisible.value) {
              isPanelVisible.value = false;
              if ('vibrate' in navigator) {
                try { navigator.vibrate(15); } catch (e) {}
              }
            }
          }, { passive: true });
        }
        
        if (bottomPanel) {
          // 防止事件传播到底层地图
          bottomPanel.addEventListener('click', (e) => {
            e.stopPropagation();
          });
        }
      }, 500); // 延迟添加确保DOM已加载
    });

    onUnmounted(() => {
      if (map) {
        map.destroy();
      }
      if (carMarker) {
        carMarker.setMap(null);
      }
      if (timer) {
        clearInterval(timer);
      }
      if (searchTimeout.value) {
        clearTimeout(searchTimeout.value);
      }
      
      document.removeEventListener('click', () => {});
    });

    return {
      inputRef,
      nearbyPOIs,
      searchVisible,
      searchKeyword,
      searchTips,
      goBack,
      onSearchFocus,
      onSearchInput,
      selectSearchTip,
      setPOIAsDestination,
      searchCurrentInput,
      isPanelVisible,
      togglePanel
    };
  }
});
</script>

<style scoped>
.map-wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #f5f5f5;
}

/* 蓝色定位圆圈样式 */
:deep(.location-circle) {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #1791fc;
  box-shadow: 0 0 0 2px white, 0 0 5px 1px rgba(0, 0, 0, 0.3);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(23, 145, 252, 0.7), 0 0 0 2px white;
  }
  70% {
    box-shadow: 0 0 0 6px rgba(23, 145, 252, 0), 0 0 0 2px white;
  }
  100% {
    box-shadow: 0 0 0 0 rgba(23, 145, 252, 0), 0 0 0 2px white;
  }
}

.back-button {
  position: absolute;
  top: 15px;
  left: 15px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  z-index: 100;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.back-button span {
  margin-left: 5px;
  font-size: 14px;
}

.container {
  width: 100%;
  height: 100%;
}

/* 面板控制按钮 */
.panel-control {
  position: absolute;
  bottom: 50%;
  right: 15px;
  left: auto;
  transform: translateY(50%);
  width: 40px;
  height: 40px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 99;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.panel-arrow {
  transition: transform 0.3s ease;
  transform: rotate(180deg);
}

.panel-arrow.is-up {
  transform: rotate(0);
}

.bottom-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  border-radius: 20px 20px 0 0;
  padding: 20px;
  box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.15);
  max-height: 65%;
  overflow-y: auto;
  transition: all 0.4s cubic-bezier(0.25, 1, 0.5, 1); /* 更平滑的动画效果 */
  transform: translateY(100%);
  z-index: 98;
  -webkit-overflow-scrolling: touch; /* 在iOS上平滑滚动 */
  padding-top: 30px; /* 为横杠区域留出空间 */
}

.bottom-panel.is-visible {
  transform: translateY(0);
}

/* 删除旧的滑动手柄 */
.bottom-panel:before {
  content: none;
}

/* 添加可点击的横杠区域 */
.handle-area {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 30px; /* 增加可点击区域高度 */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-color: white; /* 确保背景色与面板一致 */
  border-radius: 20px 20px 0 0; /* 与面板保持一致的圆角 */
  z-index: 99;
}

.handle-bar {
  width: 40px;
  height: 4px;
  background-color: #e0e0e0;
  border-radius: 4px;
}

.search-box {
  position: relative;
  margin-bottom: 20px;
}

.search-container {
  position: relative;
}

.search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-input {
  width: 100%;
  padding: 10px 10px 10px 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  font-size: 14px;
  outline: none;
  box-sizing: border-box;
  padding-right: 70px; /* 为搜索按钮留出空间 */
}

.search-button {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background-color: #007bff;
  color: white;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.search-button:active {
  background-color: #0056b3;
}

/* 已移除旧的搜索提示样式 */

.nearby-title {
  font-size: 16px;
  margin: 10px 0;
  color: #333;
}

.poi-list {
  max-height: 300px;
  overflow-y: auto;
}

.poi-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  width: 100%;
}

.poi-info {
  flex: 1;
  text-align: left;
  padding-right: 10px;
  max-width: 70%;
}

.poi-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 5px;
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.poi-distance {
  font-size: 12px;
  color: #666;
  text-align: left;
}

.set-button {
  padding: 8px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  margin-left: auto;
  min-width: 60px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.set-button:active {
  transform: scale(0.95);
  background-color: #0056b3;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.set-button:active {
  background-color: #f5f5f5;
}

.route-info {
  position: absolute;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
  width: 80%;
  max-width: 300px;
}

.route-info-panel {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 12px 15px;
}

.route-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
  text-align: center;
}

.route-detail {
  font-size: 14px;
  color: #666;
}

.route-distance, .route-time {
  margin: 5px 0;
}

.route-info-panel.route-error {
  background-color: #ffeeee;
  border-left: 4px solid #ff6666;
}

.route-destination {
  margin: 5px 0;
  font-weight: 500;
  color: #333;
}
</style>